//
//  WBPullDownRefreshControl.swift
//  SinaWeibo_Swift
//
//  Created by TianZhen on 16/4/15.
//  Copyright © 2016年 TianZhen. All rights reserved.
//

import UIKit

// 高度
private let WBPullDownRefreshControlHeight: CGFloat = 60

enum WBPullDownRefreshControlStatus: Int
{
    case Normal         // 箭头朝下，下拉刷新
    case PullToRefresh  // 箭头朝上，释放刷新
    case Refreshing     // 正在刷新
}

class WBPullDownRefreshControl: UIView {

    private var superScrollView: UIScrollView?
    
    // 默认状态
    private var status: WBPullDownRefreshControlStatus = WBPullDownRefreshControlStatus.Normal

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        // 定义frame
        let newFrame = CGRect(x: 0, y: -WBPullDownRefreshControlHeight, width: UIScreen.mainScreen().bounds.width, height: WBPullDownRefreshControlHeight)
        super.init(frame: newFrame)
        
        backgroundColor = UIColor.orangeColor()
    }
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        
        // 判断父控件是UIScrollView或其子类
        if let scrollView = newSuperview as? UIScrollView
        {
            superScrollView = scrollView
            
            // KVO 监听滚动
            superScrollView?.addObserver(self, forKeyPath: "contentOffset", options: [], context: nil)
        }
    }
    
    // kvo移除
    deinit
    {
        removeObserver(self, forKeyPath: "contentOffset")
    }
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        HMPrint("tableView滚动了: \(superScrollView?.contentOffset.y)")
    }
        
}
